//
//  PKLineProgressBar.swift
//  GoAbroad
//
//  Created by Pink Snow on 2025/5/28.
//



import UIKit

class PKLineProgressBar: UIView {

    // MARK: - Public Properties
    var progress: CGFloat = 0.0 {
        didSet {
            setProgress(progress, animated: true)
        }
    }

    var progressColor: UIColor = .systemBlue {
        didSet {
            progressLayer.backgroundColor = progressColor.cgColor
        }
    }

    var trackColor: UIColor = .systemGray5 {
        didSet {
            trackLayer.backgroundColor = trackColor.cgColor
        }
    }

    var showPercentageLabel: Bool = true {
        didSet {
            percentageLabel.isHidden = !showPercentageLabel
        }
    }

    // MARK: - Private Views
    private let trackLayer = CALayer()
    private let progressLayer = CALayer()
    private let percentageLabel = UILabel()

    // MARK: - Init
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLayers()
        setupLabel()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupLayers()
        setupLabel()
    }

    private func setupLayers() {
        layer.cornerRadius = 8
        clipsToBounds = true

        trackLayer.backgroundColor = trackColor.cgColor
        layer.addSublayer(trackLayer)

        progressLayer.backgroundColor = progressColor.cgColor
        layer.addSublayer(progressLayer)
    }

    private func setupLabel() {
        percentageLabel.font = .systemFont(ofSize: 13, weight: .medium)
        percentageLabel.textColor = .darkGray
        percentageLabel.textAlignment = .right
        percentageLabel.isHidden = !showPercentageLabel
        addSubview(percentageLabel)
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        trackLayer.frame = bounds

        let progressWidth = bounds.width * progress
        progressLayer.frame = CGRect(x: 0, y: 0, width: progressWidth, height: bounds.height)

        percentageLabel.frame = CGRect(x: 0, y: -22, width: bounds.width, height: 20)
        percentageLabel.text = "\(Int(progress * 100))%"
    }

    func setProgress(_ progress: CGFloat, animated: Bool = true) {
        let clamped = min(max(progress, 0.0), 1.0)
        self.progress = clamped

        let targetWidth = bounds.width * clamped

        if animated {
            CATransaction.begin()
            CATransaction.setAnimationDuration(0.3)
            progressLayer.frame.size.width = targetWidth
            CATransaction.commit()
        } else {
            progressLayer.frame.size.width = targetWidth
        }

        percentageLabel.text = "\(Int(clamped * 100))%"
    }
}
